<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="filterState.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in menuList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select
              v-model="filterState.state"
              placeholder="请选择状态"
              size="small"
            >
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="filterArt"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="resetArt"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="dialogVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table border stripe :data="artList" style="width: 100%">
        <el-table-column prop="title" label="文章标题">
          <!-- v-slot="对象" el-table-column 内部传递过来的 -->
          <template v-slot="{ row }">
            <el-link @click="showDetail(row.id)" type="success">{{
              row.title
            }}</el-link></template
          >
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{ row }">{{ formatDate(row.pubDate) }}</template>
        </el-table-column>
        <el-table-column prop="state" label="状态"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="delArt(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="block" style="margin-top: 15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="q.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- dialog -->
    <!-- 所有字段清空
    resetFields方法是根据prop对应的数据来清空的 -->
    <el-dialog
      @closed="dialogclose()"
      title="发表文章"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      fullscreen
    >
      <el-form
        ref="pubForm"
        :model="pubForm"
        :rules="pubRules"
        label-width="80px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            class="length"
            v-model="pubForm.cate_id"
            placeholder="请选择文章分类"
          >
            <!--   :value="item.id"
          将来给后台传递的数据-->
            <el-option
              v-for="item in menuList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor
            @blur="$refs.pubForm.validateField('content')"
            v-model="pubForm.content"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img
            v-if="cover"
            :src="cover"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <img
            v-else
            src="../../../assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="coverChange"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="a" @click="pubArt('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="pubArt('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
    <!-- 详情dialog -->
    <el-dialog title="文章预览" :visible.sync="dVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://www.liulongbin.top:3008' + artDetail.cover_img"
        alt=""
      />

      <div v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data() {
    return {
      cover: '',
      dVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      filterState: {
        cate_id: '',
        state: ''
      },
      dialogVisible: false,
      total: 0,
      menuList: [],
      artList: [],
      artDetail: [],
      pubForm: {
        title: '',
        cate_id: '',
        cover_img: '',
        state: '',
        content: ''
      },
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getCartList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getCartList()
    },
    handleClose(done) {
      // $confirm参数一：内容，
      // 参数二：标题
      // 参数三：配置对象，可以设置type
      this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示', {
        type: 'warning'
      })
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    async getMenuList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      this.menuList = res.data
    },
    // 图片预览
    coverChange(e) {
      const file = e.target.files[0]
      if (file) {
        // 将文件对象转为URL
        this.cover = URL.createObjectURL(file)
        this.pubForm.cover_img = file
        // console.log('用户选择了图片')
        this.$refs.pubForm.validateField('cover_img')
      } else {
        this.cover = ''
        this.pubForm.cover_img = ''
      }
    },
    dialogclose() {
      // 清空表单
      this.$refs.pubForm.resetFields()
      // 清空预览图片
      this.cover = ''
    },
    pubArt(state) {
      // 设置state
      this.pubForm.state = state
      // 兜底校验
      this.$refs.pubForm.validate(async (valid) => {
        if (!valid) return
        // console.log('我要发请求')
        // 当求请求接口为FormData 格式时必须先转为FormData
        const fd = new FormData()
        Object.keys(this.pubForm).forEach((k) => fd.append(k, this.pubForm[k]))
        // 发请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // 根据结果提示用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭dialog
        this.dialogVisible = false
        // 更新数据
        this.getCartList()
      })
    },
    async getCartList() {
      // 发送请求
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      // console.log(res)
      this.artList = res.data
      this.total = res.total
    },
    // 日期
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    filterArt() {
      this.q.pagenum = 1
      this.q.cate_id = this.filterState.cate_id
      this.q.state = this.filterState.state
      this.getCartList()
    },
    resetArt() {
      // 还原q再发请求
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.filterState = {
        cate_id: '',
        state: ''
      }
      this.getCartList()
    },
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: {
          id
        }
      })
      this.artDetail = res.data
      this.dVisible = true
    },
    delArt(id) {
      this.$confirm('确定删除该文章吗？', '提示', {
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('/my/article/info', {
            params: {
              id
            }
          })
          // return 执行之后，将退出所在的方法，而不再执行后面没有执行的语句
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)
          // 如果当前数组长度只有1说明最后一条数据已经被删除了，所以需要让pagenum--，但是pagenum最小只能减到1，所以需要加一 && this.q.pagenum>1
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            // 所以这里不能写return，而是写一个大括号
            this.q.pagenum--
          }
          this.getCartList()
        })
        .catch((e) => {})
    }
  },
  created() {
    this.getMenuList()
    this.getCartList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.length.el-select {
  width: 100%;
}
/deep/ .quill-editor .ql-editor {
  height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.a {
  width: 65px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
